package com.jsm.tf.net.handler;

import com.jsm.tf.entity.User;
import com.jsm.tf.net.invoke.CommandInvoker;
import com.jsm.tf.net.message.Message;
import com.jsm.tf.net.session.ISessionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ChannelHandler.Sharable
@Slf4j
public class ClientMessageHandler extends ChannelInboundHandlerAdapter {
    @Resource
    private ISessionManager sessionManager;

    @Resource
    private CommandInvoker invoker;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        invoker.invoke(message, ctx.channel());
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        User user = sessionManager.getUserByChannel(ctx.channel());
        if (user != null) {
            log.info("用户:{} 已断开连接", user.getNickname());
            sessionManager.unbind(ctx.channel());
        }else{
            log.info("channel:{} 已断开连接", ctx.channel());
        }
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        User user = sessionManager.getUserByChannel(ctx.channel());
        if (user != null) {
            log.error("用户:{} 发生异常 ", user.getNickname(), cause);
//            sessionManager.unbind(ctx.channel());
        }else{
//            sessionManager.unbind(ctx.channel());
            log.info("channel:{} 发生异常", ctx.channel());
        }
        super.exceptionCaught(ctx, cause);
    }
}
